/*
  ajax请求函数模块
  返回值: promise对象(异步返回的数据是: response.data)
  添加缓存功能
*/
import axios from 'axios'
import Store from './store.js'
export default function ajax (url, data = {}, type = 'GET') {
  // 查看缓存是否存在
  let cacheKey = url + JSON.stringify(data)
  let cacheData = Store.fetch(cacheKey)
  if (cacheData) {
    return new Promise((resolve, reject) => {
      resolve(cacheData) // 返回缓存中值
    })
  } else {
    return new Promise(function (resolve, reject) {
      // 执行异步ajax请求
      let promise
      if (type === 'GET') {
        // 准备url query参数数据
        let dataStr = '' // 数据拼接字符串
        Object.keys(data).forEach(key => {
          dataStr += key + '=' + data[key] + '&'
        })
        if (dataStr !== '') {
          dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
          url = url + '?' + dataStr
        }
        // 发送get请求
        promise = axios.get(url)
      } else {
        // 发送post请求
        promise = axios.post(url, data)
      }
      promise.then(function (response) {
        // 成功了调用resolve()
        resolve(response.data)
        Store.save(cacheKey, response.data) // 放入缓存
      }).catch(function (error) {
        // 失败了调用reject()
        reject(error)
      })
    })
  }
}

/*
const response = await ajax()
const result = response.data

const resule = await ajax()
 */
